package org.example.tools;

import dev.langchain4j.agent.tool.Tool;
import dev.langchain4j.agent.tool.ToolExecutionRequest;
import dev.langchain4j.agent.tool.ToolSpecification;
import dev.langchain4j.agent.tool.ToolSpecifications;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ToolExecutionResultMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.output.Response;
import org.example.utils.ModelUtils;
import org.springframework.format.annotation.DateTimeFormat;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 调用工具方法，执行扩展功能
 * 获取当前时间
 * @Author codeYang
 * @Date 2025/3/16 18:44
 * @Version 1.0
 */
public class ChatTools {

    @Tool("获取今天日期")
    public static String getData() {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return now.format(formatter);
    }

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        ChatLanguageModel chatLanguageModel = ModelUtils.getZhipuAiModel();

        // 设置工具类
        ToolSpecification specification = ToolSpecifications.toolSpecificationFrom(ChatTools.class.getMethod("getData"));

        UserMessage userMessage = new UserMessage("今天日期是？");

        AiMessage aiMessage = chatLanguageModel.generate(List.of(userMessage), specification).content();

        System.out.println(aiMessage);
        if (aiMessage.hasToolExecutionRequests()) {
            for (ToolExecutionRequest toolExecutionRequest : aiMessage.toolExecutionRequests()) {
                // 获取方法名称
                String name = toolExecutionRequest.name();
                Method method = ChatTools.class.getMethod(name);

                Object invoke = method.invoke(null);

                if (invoke instanceof String message) {
                    System.out.println(message);
                    ToolExecutionResultMessage resultMessage = ToolExecutionResultMessage.from(toolExecutionRequest.id(), toolExecutionRequest.name(), message);

                    Response<AiMessage> generate = chatLanguageModel.generate(List.of(userMessage, aiMessage, resultMessage));

                    String answer = generate.content().text();
                    System.out.println(answer);

                } else {
                    System.out.println(invoke);
                }
            }
        }
    }
}
